<?php

namespace App\Http\Controllers;

use App\Models\User;
use Gregwar\Captcha\CaptchaBuilder;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Session;
use Spatie\Permission\Models\Permission;
use Spatie\Permission\Models\Role;

class UserController extends Controller
{
    /*
     * 登录
     */
    public function login() {
        $data = [
            'title' => 'DT代理分销平台',
            'website' => 'https://www.changliang.top',
            'icp' => '鲁ICP备2021022800号',
            'captcha' => $this->captcha()
        ];
        return view('login', $data);
    }
    /**
     * 登录验证
     */
    public function verifyLogin(Request $request) {
        $status = 200;
        $captcha = $request->input('captcha');
        if (strtolower($captcha) == Session::get('phrase')) {
            Session::forget('phrase');
        } else {
            return '验证码错误';
        }
        $arr = $request->only('name', 'password');
        if (Auth::attempt($arr)) {
            $status = 200;
        } else {
            $status = '用户名或密码错误';
        }
        return $status;
    }
    /**
     * 验证码
     */
    public function captcha() {
        $ca = new CaptchaBuilder();
        $text = strtolower($ca->getPhrase());
        Session::put('phrase', $text);
        return $ca->build()->inline();
    }
    /**
     * 角色管理
     */
    public function role() {
        return view('user.role');
    }
    /**
     * 角色列表api
     */
    public function roleList(Request $request) {
        $limit = empty($request->get('limit')) ? 15 : $request->get('limit');
        $roles = Role::orderByDesc('id')->paginate($limit);
        return $roles;
    }
    /**
     * 创建角色
     */
    public function createRole() {
        $permission = Permission::all();
        return view('user.createRole', ['permission' => $permission]);
    }
    /**
     * 保存角色
     */
    public function storeRole(Request $request) {
        $name = $request->input('name');
        $permission = $request->input('permissions');
        $code = 200;
        try {
            DB::beginTransaction();
            //创建角色
            $is_success = Role::create(['name' => $name]);
            //赋予权限
            if ($is_success) {
                $role = Role::findByName($name);
                foreach ($permission as $k=>$v) {
                    $permiss = Permission::findById($k);
                    $role->givePermissionTo($permiss);
                }
            }
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $code = 1001;
        }
        return $this->toJSON($code);
    }
    /**
     * 用户列表
     */
    public function index() {
        return view('user.index');
    }
    /**
     * 用户列表api
     */
    public function userList(Request $request) {
        $limit = empty($request->get('limit')) ? 15 : $request->get('limit');
        $user = User::with('roles')->orderByDesc('id')->paginate($limit);
        return $user;
    }
    /**
     * 创建用户
     */
    public function createUser() {
        $role = Role::all();
        return view('user.createUser', ['role' => $role]);
    }
    /**
     * 保存用户
     */
    public function storeUser(Request $request) {
        $code = 200;
        $arr['name'] = $request->input('name');
        $arr['password'] = bcrypt($request->input('password'));
        $roleId = $request->input('role');
        try {
            DB::beginTransaction();
            $user = new User($arr);
            $user->save();
            $user->assignRole($roleId);
            DB::commit();
        } catch (\Exception $e) {
            DB::rollBack();
            $code = 1001;
        }
        return $this->toJSON($code);
    }
}
